using B.S.Domain.CangKu;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using B.S.Data.MES.API.Applications.CangKu.Command;

namespace B.S.Data.MES.API.Applications.CangKu.CommandHandlers
{
    public class AddCangKuCommandHandler : IRequestHandler<AddCangKuCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<CangKuinfo> _cangKuRepository;
        private readonly IMapper _mapper;
        private readonly IMediator _mediator;

        public AddCangKuCommandHandler(IBaseRepository<CangKuinfo> cangKuRepository, IMapper mapper, IMediator mediator)
        {
            _cangKuRepository = cangKuRepository;
            _mapper = mapper;
            _mediator = mediator;
        }

        public async Task<APIRequst<int>> Handle(AddCangKuCommand request, CancellationToken cancellationToken)
        {
            var su = _cangKuRepository.GetAll().Count(x => x.CangkuNo == request.CangkuNo);
            var cangKu = _mapper.Map<CangKuinfo>(request);
            cangKu.CreateTime = DateTime.Now;
            if (su >= 1)
            {
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = "编号重复"
                };

            }
            await _cangKuRepository.Add(cangKu);
            
            // 添加成功后调用Tel的添加方法
            await _mediator.Send(new AddTelCommand { CanType = request.CangName }, cancellationToken);
            
            return new APIRequst<int>
            {
                Code = RequstCode.成功,
                Msg = RequstCode.成功.ToString()
            };
        }
    }
}